const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || "43.143.253.188",
  port: parseInt(process.env.DB_PORT || "3306", 10),
  user: process.env.DB_USER || "nextjs",
  password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
  database: process.env.DB_NAME || "nextjs",
  charset: 'utf8mb4',
  timezone: '+08:00',
};

// 模拟WebSocket查询逻辑
async function testMapQueries() {
  let connection;
  
  try {
    console.log('🔍 测试地图查询功能...');
    
    // 连接数据库
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功！');
    
    // 测试1418指令 - 根据areaId查询子区域
    console.log('\n📋 测试1418指令 (根据areaId查询子区域):');
    console.log('='.repeat(60));
    
    const testCases1418 = [
      { areaId: 100, expected: ['许昌', '洛阳', '长安'] },
      { areaId: 19, expected: ['成都', '南中', '汉中'] },
      { areaId: 43, expected: ['建业', '长沙', '江陵'] },
    ];
    
    for (const testCase of testCases1418) {
      console.log(`\n🔍 查询 areaId=${testCase.areaId}:`);
      
      const [areas] = await connection.execute(`
        SELECT id, name, extension 
        FROM map_areas 
        WHERE parent_id = ? 
        ORDER BY id ASC
      `, [testCase.areaId]);
      
      const result = areas.map(area => ({
        id: area.id,
        name: area.extension ? `${area.name}${area.extension}` : area.name
      }));
      
      console.log('📤 发送的数据:', JSON.stringify({c: 1418, d: {areaId: testCase.areaId}}));
      console.log('📥 接收到的数据:', JSON.stringify({
        act_id: 1418,
        code: 0,
        list: result
      }));
      
      // 验证结果
      const actualNames = result.map(r => r.name);
      const isMatch = testCase.expected.every(expected => 
        actualNames.some(actual => actual.includes(expected))
      );
      
      console.log(`✅ 结果验证: ${isMatch ? '通过' : '失败'}`);
      if (!isMatch) {
        console.log(`   期望: ${testCase.expected.join(', ')}`);
        console.log(`   实际: ${actualNames.join(', ')}`);
      }
    }
    
    // 测试1436指令 - 根据pid查询子区域
    console.log('\n\n📋 测试1436指令 (根据pid查询子区域):');
    console.log('='.repeat(60));
    
    const testCases1436 = [
      { pid: 289, expected: ['新手村', '陈留', '九里山', '芒砀山'] },
      { pid: 302, expected: ['官渡', '虎牢关', '乌巢', '函谷关'] },
      { pid: 304, expected: ['华山', '潼关', '五丈原'] },
      { pid: 70, expected: ['落凤坡', '广汉', '峨眉山'] },
      { pid: 111, expected: ['云南', '泸水', '西洱湖'] },
      { pid: 117, expected: ['子午谷', '街亭', '上方谷'] },
      { pid: 154, expected: ['广陵'] },
      { pid: 212, expected: ['巴陵', '洞庭湖', '湘水'] },
      { pid: 264, expected: ['麦城', '长坂坡', '夷陵'] },
    ];
    
    for (const testCase of testCases1436) {
      console.log(`\n🔍 查询 pid=${testCase.pid}:`);
      
      const [areas] = await connection.execute(`
        SELECT id, name, extension 
        FROM map_areas 
        WHERE parent_id = ? 
        ORDER BY id ASC
      `, [testCase.pid]);
      
      const result = areas.map(area => ({
        id: area.id,
        name: area.extension ? `${area.name}${area.extension}` : area.name
      }));
      
      console.log('📤 发送的数据:', JSON.stringify({c: 1436, d: {pid: testCase.pid}}));
      console.log('📥 接收到的数据:', JSON.stringify({
        act_id: 1436,
        code: 0,
        list: result
      }));
      
      // 验证结果
      const actualNames = result.map(r => r.name);
      const isMatch = testCase.expected.every(expected => 
        actualNames.some(actual => actual.includes(expected))
      );
      
      console.log(`✅ 结果验证: ${isMatch ? '通过' : '失败'}`);
      if (!isMatch) {
        console.log(`   期望: ${testCase.expected.join(', ')}`);
        console.log(`   实际: ${actualNames.join(', ')}`);
      }
    }
    
    // 测试完整的查询流程
    console.log('\n\n🔄 测试完整查询流程:');
    console.log('='.repeat(60));
    
    console.log('\n📋 流程1: 查询中原地区 -> 许昌 -> 许昌的子区域');
    
    // 1. 查询中原地区的城市
    const [cities] = await connection.execute(`
      SELECT id, name FROM map_areas WHERE parent_id = 100 ORDER BY id ASC
    `);
    console.log('🏛️ 中原地区的城市:', cities.map(c => `${c.name}(ID:${c.id})`).join(', '));
    
    // 2. 选择许昌，查询其子区域
    const [xuchangAreas] = await connection.execute(`
      SELECT id, name, extension FROM map_areas WHERE parent_id = 289 ORDER BY id ASC
    `);
    console.log('🏙️ 许昌的子区域:', xuchangAreas.map(a => 
      `${a.extension ? a.name + a.extension : a.name}(ID:${a.id})`
    ).join(', '));
    
    console.log('\n📋 流程2: 查询蜀地 -> 成都 -> 成都的子区域');
    
    // 1. 查询蜀地的城市
    const [shuCities] = await connection.execute(`
      SELECT id, name FROM map_areas WHERE parent_id = 19 ORDER BY id ASC
    `);
    console.log('🏛️ 蜀地的城市:', shuCities.map(c => `${c.name}(ID:${c.id})`).join(', '));
    
    // 2. 选择成都，查询其子区域
    const [chengduAreas] = await connection.execute(`
      SELECT id, name, extension FROM map_areas WHERE parent_id = 70 ORDER BY id ASC
    `);
    console.log('🏙️ 成都的子区域:', chengduAreas.map(a => 
      `${a.extension ? a.name + a.extension : a.name}(ID:${a.id})`
    ).join(', '));
    
    console.log('\n✅ 地图查询功能测试完成！');
    
  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 执行测试
if (require.main === module) {
  testMapQueries()
    .then(() => {
      console.log('✅ 测试完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('❌ 测试失败:', error);
      process.exit(1);
    });
}

module.exports = { testMapQueries };
